/**
 * Project Name : cloudlead-common-api
 * File Name : FileApiHistoryService.java
 * Package Name : com.cloudlead.common.worker.impl
 * Date : 2014年7月15日下午5:40:20
 * Copyright (c) 2014, cloudlead.com.cn All Rights Reserved.
 */
package com.cloudlead.common.worker.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import com.cloudlead.common.worker.ActionHistory;
import com.cloudlead.common.worker.ApiHistoryService;
import com.cloudlead.common.lang.serialize.BeanSerializeException;
import com.cloudlead.common.lang.serialize.JSON;

/**
 *
 * @Description TODO(这里用一句话描述这个类的作用)
 *
 * @date 2014年7月15日 下午5:40:20
 * @author 陆林(lulin@cloudlead-partners.com)
 * @version 2.0
 * @since 2.0
 */
@Service
public class FileApiHistoryService implements ApiHistoryService {

    private File historyFileRepo;

    ExecutorService threadPool;

    @PostConstruct
    public void startService() {
        // 创建临时目录
        String tmpPath = System.getProperty("java.io.tmpdir");
        historyFileRepo = new File(tmpPath, "_API_History");
        historyFileRepo.mkdirs();

        threadPool = Executors.newCachedThreadPool();
    }

    @PreDestroy
    public void stopService() {
        threadPool.shutdownNow();

        if (null != historyFileRepo && historyFileRepo.exists()) {
            File[] listFiles = historyFileRepo.listFiles();
            for (File file : listFiles) {
                file.delete();
            }
            historyFileRepo.delete();
        }
    }

    /*
     * @see
     * com.cloudlead.common.worker.ApiHistoryService#recordHistory(com.cloudlead
     * .common.api.ActionHistory)
     */
    @Override
    public void recordHistory(final ActionHistory history) {
        threadPool.execute(() -> {
            try {
                String string = JSON.toString(history);
                File file = new File(historyFileRepo, history.getAction()
                        + "_" + history.getDate());
                FileOutputStream out = null;
                try {
                    out = new FileOutputStream(file);
                    out.write(string.getBytes());
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    if (null != out) {
                        try {
                            out.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        out = null;
                    }
                }
            } catch (BeanSerializeException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        });

    }

    /*
     * @see com.cloudlead.common.worker.ApiHistoryService#loadAll()
     */
    @Override
    public List<ActionHistory> loadAll() {
        List<ActionHistory> list = new ArrayList<>();
        File[] listFiles = historyFileRepo.listFiles();
        if (null != listFiles) {
            for (File file : listFiles) {
                FileInputStream in = null;
                StringBuilder json = new StringBuilder();
                try {
                    in = new FileInputStream(file);
                    byte[] buf = new byte[1024];
                    int i = 0;
                    while ((i = in.read(buf)) != -1) {
                        json.append(new String(buf, 0, i));
                    }

                    ActionHistory history = JSON.toBean(json.toString(),
                            ActionHistory.class);
                    list.add(history);
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    if (null != in) {
                        try {
                            in.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        in = null;
                    }
                }
            }
        }
        return list;
    }

}
